package com.hsq.udp;

import java.io.IOException;
import java.net.*;

public class UDPSenderB {
    public static void main(String[] args) throws IOException {
        DatagramSocket socket = new DatagramSocket(9998);
        byte[] buf = "Hello 明天去上课~".getBytes();
        DatagramPacket packet =
                new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.120.1"), 9999);
        socket.send(packet);

        buf = new byte[1024];//最大64k 1024 * 64
        packet = new DatagramPacket(buf, buf.length);
        //如果有数据发送到端口9999，就会接收数据
        //如果没有数据包发送到本机9999端口，就会阻塞等待
        System.out.println("接收端A 等待接收数据......");
        socket.receive(packet);
        //将packet进行拆包
        int lenget = packet.getLength();
        byte[] data = packet.getData();
        String s = new String(data, 0, lenget);
        System.out.println(s);

        socket.close();
        System.out.println("Sender B exit...");
;    }
}
